import os
import pandas as pd

globalfile_root_path = "/Users/juphoon/project/SoulslikeTRPGTemplate/Scripts/Global"
resourcePaths = []
customClassesPaths = []


def clear_directory(directory):
    if os.path.exists(directory):
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            if file_path.endswith(".gd"):
                os.unlink(file_path)
    else:
        os.makedirs(directory)


def generate_godot_script(csv_file, gd_file):
    try:
        df = pd.read_csv(csv_file)
        class_name = os.path.splitext(os.path.basename(csv_file))[0]
        variables = df.columns.tolist()
        
        with open(gd_file, 'w') as f:
            f.write(f"class {class_name}:\n")
            
            for var in variables:
                f.write(f"    var {var}\n")
            
            f.write("\n    static var configs:Array\n")
            f.write("    static var configsDict:Dictionary\n")

            hasGroupColumn = False
            for variable in variables:
                if variable == "groupId":
                    hasGroupColumn = True
        
            if hasGroupColumn:
                f.write("    static var groupConfigArrDict:Dictionary\n\n")
                f.write("    static func processData():\n")
                f.write('        print("processData")\n')
                f.write('        for config in configs:\n')
                f.write('            if not groupConfigArrDict.has(config.groupId):\n')
                f.write('                groupConfigArrDict[config.groupId] = []\n')
                f.write('            groupConfigArrDict[config.groupId].append(config)\n')
        
    except Exception as e:
        print(f"Error generating Godot script from {csv_file}: {e}")


def convert_csv_to_godot_scripts(src_dir, dest_dir):
    # 清空目标目录
    clear_directory(dest_dir)

    gd_filename_list = []
    
    # 遍历源目录中的所有CSV文件
    for filename in os.listdir(src_dir):
        if filename.endswith(".csv"):
            csv_file = os.path.join(src_dir, filename)
            gd_filename_nopostfix = os.path.splitext(filename)[0]
            gd_filename = gd_filename_nopostfix + ".gd"
            gd_file = os.path.join(dest_dir, gd_filename)

            gd_filename_list.append(gd_filename_nopostfix)
            
            # 生成Godot脚本文件
            generate_godot_script(csv_file, gd_file)
            print(f"Generated {gd_file} from {csv_file}")

            #搜索并将所有的spriteFrames资源保存到一个集合中
            if "ResourcePreloadConfig.csv" in filename:
                save_resoucepath_values(csv_file)

            if "CustomClassesConfig.csv" in filename:
                save_customclasses_paths(csv_file)


    # 生成清单脚本文件
    meta_file = os.path.join(dest_dir, "ConfigClasses.gd")
    generate_meta_script(meta_file, gd_filename_list)

    #生成资源预加载文件
    resource_preload_file = os.path.join(globalfile_root_path, "ResourcePreload.gd")  
    generate_resource_preload_script(resource_preload_file)

    #生成自定义脚本加载文件
    customclasses_preload_file = os.path.join(globalfile_root_path, "CustomClasses.gd")
    generate_customclasses_script(customclasses_preload_file)


def get_filename_from_path(path):
    # 提取文件名（包含扩展名）
    filename_with_ext = os.path.basename(path)
    # 去掉扩展名
    filename, _ = os.path.splitext(filename_with_ext)
    return filename


def save_resoucepath_values(csv_file):
    try:
        df = pd.read_csv(csv_file)
        global resourcePaths
        resourcePaths.extend(df['resourcePath'].dropna().tolist())
    except Exception as e:
        print(f"Error processing spriteFrames from {csv_file}: {e}")


def save_customclasses_paths(csv_file):
    try:
        df = pd.read_csv(csv_file)
        global customClassesPaths
        customClassesPaths.extend(df['path'].dropna().tolist())
    except Exception as e:
        print(f"Error processing spriteFrames from {csv_file}: {e}")


def generate_customclasses_script(customclasses_preload_file):
    try:
        with open(customclasses_preload_file, 'w') as f:
            f.write(f"extends Node\n\n")

            for path in customClassesPaths:
               className = get_filename_from_path(path)
               f.write(f'var {className} = preload("{path}").{className}\n')

    except Exception as e:
        print(f"Error generating resource preload script {customclasses_preload_file}: {e}")


def generate_resource_preload_script(resource_preload_file):
    try:
        with open(resource_preload_file, 'w') as f:
            f.write(f"extends Node\n\n")
            f.write("var resources = {}\n\n")
            f.write(f"func _ready():\n")
            f.write("    resources = {\n")

            for resourcePath in resourcePaths:
               f.write(f'        "{get_filename_from_path(resourcePath)}": preload("{resourcePath}"),\n')

            f.write("    }\n\n")

    except Exception as e:
        print(f"Error generating resource preload script {resource_preload_file}: {e}")


def generate_meta_script(meta_file, gd_filename_list):
    try:
        with open(meta_file, 'w') as f:
            f.write(f"extends Node\n\n")

            for filename in gd_filename_list:
               f.write(f'var {filename} = preload("res://Scripts/Configs/{filename}.gd").{filename}\n')
            
            f.write("\nfunc _ready():\n")
            for filename in gd_filename_list:
               f.write(f'    GlobalData.loadConfig("{filename}.csv", ConfigClasses.{filename})\n')

    except Exception as e:
        print(f"Error generating meta script {meta_file}: {e}")


if __name__ == "__main__":
    src_dir = "/Users/juphoon/project/SoulslikeTRPGTemplate/Assets/Configs/CSV"  # 源目录路径
    dest_dir = "/Users/juphoon/project/SoulslikeTRPGTemplate/Scripts/Configs"  # 目标目录路径
    
    convert_csv_to_godot_scripts(src_dir, dest_dir)
